const request = require('../../utils/request');

Page({
  data: {
    nickname: '',
    saving: false
  },

  onLoad() {
    const app = getApp();
    const userId = app.globalData.userId;
    if (!userId) {
      wx.reLaunch({ url: '/pages/login/login' });
      return;
    }
    this.loadCurrentNickname(userId);
  },

  async loadCurrentNickname(userId) {
    try {
      const res = await new Promise((resolve, reject) => {
        wx.request({
          url: request.buildUrl(`/api/users/${userId}`),
          method: 'GET',
          header: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${wx.getStorageSync('token')}`
          },
          success: (r) => resolve(r.data),
          fail: reject
        });
      });

      if (res.success && res.data) {
        this.setData({ nickname: res.data.nickname || '' });
      }
    } catch (e) {
      console.error('加载昵称失败:', e);
    }
  },

  onNicknameInput(e) {
    this.setData({ nickname: e.detail.value || '' });
  },

  async onSaveNickname() {
    const app = getApp();
    const userId = app.globalData.userId;
    if (!userId) {
      wx.showToast({ title: '请先登录', icon: 'none' });
      return;
    }

    const nickname = (this.data.nickname || '').trim();
    if (!nickname) {
      wx.showToast({ title: '昵称不能为空', icon: 'none' });
      return;
    }

    this.setData({ saving: true });
    try {
      const res = await new Promise((resolve, reject) => {
        wx.request({
          url: request.buildUrl(`/api/users/${userId}`),
          method: 'PUT',
          data: { nickname },
          header: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${wx.getStorageSync('token') || ''}`
          },
          success: (r) => resolve(r.data),
          fail: reject
        });
      });

      if (res && res.success) {
        wx.showToast({ title: '保存成功', icon: 'success' });
        setTimeout(() => {
          wx.navigateBack();
        }, 600);
      } else {
        wx.showToast({ title: (res && res.message) || '保存失败', icon: 'none' });
      }
    } catch (e) {
      console.error('保存昵称失败:', e);
      wx.showToast({ title: '保存失败，请稍后再试', icon: 'none' });
    } finally {
      this.setData({ saving: false });
    }
  }
});
